var request = require('request');
var cheerio = require('cheerio');
var Promise = require('bluebird');
async function requestAsync(url) {
  return new Promise((resolve, reject) => {
    request(url,function(error,response,body){
      if(!error){
        resolve(body);
      }else{
        //console.log(body);
        //reject('Error: '+ error);
      }
    })
  });
}
exports.api = {
  get_data: async function(ctx,next){
    var items = [];
    for(let page =2;page< 5;page++){
      var searchWord = encodeURIComponent(ctx.request.body.searchWord);
      var url = 'http://search.faloo.com/cse/search?q=' + searchWord
        + '&p=' + page + '&s=8180149771949009960&nsid=&entry=1&area=1';
      var body = await requestAsync(url);
      var $ = cheerio.load(body);
      for(let i = 0; i < 10; i++){
        var href = $('.result-game-item-title-link').eq(i).attr('href');
        var link = $('.result-game-item-title-link').eq(i).attr('title');
        var num = $('.result-game-item-info').eq(i).children('.result-game-item-info-tag').eq(-2)
          .children('.result-game-item-info-tag-title').eq(-1).text();

        if(parseInt(num) > parseInt(ctx.request.body.wordNum)){
          let newItem = {
            href: href,
            link: link,
            num: num
          }
          items.push(newItem);
        }
      }
    }
    ctx.body = {
      items: items
    }
  }
}